<template>
	<div class="system-role-dialog-container energy-from energy-dialog energy-tree">
		<el-dialog center align-center v-model="state.dialog.isShowDialog" width="40%" @close="resetData">
			<template #header="{ titleClass }">
				<div :class="titleClass">
					{{ state.dialog.isAssign ? '分配权限' : '查看权限' }}
				</div>
			</template>
			<el-form ref="roleDialogFormRef" :model="state.ruleForm" :rules="state.rules" size="default" label-width="90px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="角色名称" prop="name">
							<el-input v-model="state.ruleForm.name" placeholder="请输入角色名称" clearable disabled></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="角色权限" prop="menuIds">
							<el-tree
								ref="treeRef"
								:data="state.menuData"
								:props="state.menuProps"
								node-key="id"
								:default-checked-keys="state.defaultChecked"
								:default-expanded-keys="state.defaultChecked"
								show-checkbox
								check-strictly
								class="menu-data-tree"
								@check="handleCheck"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<div class="flex row-center mt10 mb10">
				<div class="btn3" @click="onCancel">
					<el-icon> <ele-Close /> </el-icon><span class="ml6">{{ state.dialog.isAssign ? '取 消' : '关 闭' }}</span>
				</div>
				<div class="btn1 ml10" @click="onSubmit" v-if="state.dialog.isAssign">
					<el-icon> <ele-Check /> </el-icon><span class="ml6">保 存</span>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemRoleDialog">
import { reactive, ref, nextTick } from 'vue';
import { useRoleApi } from '/@/api/role/index';
import { ElNotification } from 'element-plus';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const treeRef = ref();
// 定义变量内容
const roleDialogFormRef = ref();
const state: any = reactive({
	ruleForm: {
		id: '', // 角色id
		name: '', // 角色名称
		roleKey: '', // 角色标识
		status: '0', // 角色状态
		remark: '', // 角色描述
		type: 0, // 0系统类型(不可删除) 1用户类型(可删除)
		menuIds: [],
	},
	menuData: [], // 所有权限
	allMenuData: [], // 总菜单权限树
	defaultChecked: [], // 默认选中的id集合
	menuProps: {
		children: 'childList',
		label: 'title',
		disabled: 'disabled',
	},
	dialog: {
		isShowDialog: false,
		isAssign: true,
	},
	rules: {
		menuIds: [{ required: true, message: '请选择角色权限', trigger: 'blur' }],
	},
});

// 打开弹窗
const openDialog = (row: any, isAssign: Boolean) => {
	state.dialog.isShowDialog = true;
	state.ruleForm.id = row.id;
	state.ruleForm.name = row.name;
	state.ruleForm.roleKey = row.roleKey;
	state.ruleForm.status = row.status;
	state.ruleForm.remark = row.remark;
	state.ruleForm.type = row.type;
	nextTick(() => {
		getCheckedRoles(row.id);
	});

	if (isAssign) {
		state.dialog.isAssign = true;
	} else {
		state.dialog.isAssign = false;
	}
};

// 根据id获取角色详情-已选中的角色(selected  0否 1是)
const getCheckedRoles = async (id: string) => {
	const { data } = await useRoleApi().getRoleDetailById(id);
	state.menuData = [...data.menus];

	let tileData: any = [];
	function changMenuData(data: []) {
		data.forEach((item: any) => {
			state.dialog.isAssign ? (item.disabled = 0) : (item.disabled = 1);
			tileData.push(item);
			if (item.childList && item.childList.length > 0) {
				changMenuData(item.childList);
			}
		});
	}

	changMenuData(data.menus);

	state.defaultChecked = [];

	tileData.map((item: any) => {
		if (item.selected !== 0) {
			state.defaultChecked.push(item.id);
		}
	});

	nextTick(() => {
		handleCheck();
	});
};

//获取选中的数据
const handleCheck = () => {
	// 树形数据扁平化
	let newTileData: any = [];
	function changMenuData(data: []) {
		data.forEach((item: any) => {
			newTileData.push(item);
			if (item.childList && item.childList.length > 0) {
				changMenuData(item.childList);
			}
		});
	}
	changMenuData(state.menuData);

	// 过滤出需要的数据
	state.ruleForm.menuIds = [];
	newTileData.map((i: any) => {
		treeRef.value.getCheckedNodes().map((item: any) => {
			if (i.id == item.id) {
				state.ruleForm.menuIds.push(item.id);
				// state.ruleForm.menuIds.push({
				// 	menuId: item.id,
				// 	roleId: state.ruleForm.id,
				// });
			}
		});
	});
};

// 新增权限
const handleAssignPermissions = async () => {
	const data = await useRoleApi().updateRole(state.ruleForm);
	if (data.code == 200) {
		emit('refresh');
		ElNotification({
			title: '提示',
			message: '分配权限成功',
			position: 'top-right',
			type: 'success',
		});
	}
};

// 提交
const onSubmit = () => {
	roleDialogFormRef.value.validate((valid: any) => {
		if (valid) {
			handleAssignPermissions();
		} else {
			ElNotification({
				title: '提示',
				message: '权限分配失败,请选择角色权限',
				position: 'top-right',
				type: 'error',
			});
		}
		closeDialog();
	});
};

// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};

// 取消
const onCancel = () => {
	closeDialog();
};

// 表单清空
const resetData = () => {
	nextTick(() => {
		roleDialogFormRef.value.resetFields();
		state.defaultChecked = [];

		state.ruleForm = {
			id: '', // 角色id
			name: '', // 角色名称
			roleKey: '', // 角色标识
			status: '0', // 角色状态
			remark: '', // 角色描述
			type: 0, // 0系统类型(不可删除) 1用户类型(可删除)
			menuIds: [
				// {
				// 	menuId: '', // 菜单id
				// 	roleId: '', // 角色id
				// },
			], // 权限关联关系集合
		};

		state.menuData = [];
	});
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
:deep(.el-dialog__header) {
	width: 100%;
	height: 60px;
	background-color: #5e8dff;
}

:deep(.el-dialog__header .el-dialog__title) {
	color: #fff;
}

:deep(.el-dialog__header .el-dialog__close) {
	color: #fff;
}

.system-role-dialog-container {
	.menu-data-tree {
		width: 100%;
		border: 1px solid #6090f8;
		border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
		padding: 5px;
	}
}
</style>
